package com.ssyc.gsk_teacher.activity;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.Constants;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.BqaManager;
import com.ssyc.common.manager.SrfManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.gsk_teacher.R;
import com.ssyc.gsk_teacher.adapter.LeaveRvAdapter;
import com.ssyc.gsk_teacher.bean.ClassInfo;
import com.ssyc.gsk_teacher.bean.LeaveInfo;
import com.ssyc.gsk_teacher.utils.ClassPoputil;
import com.ssyc.gsk_teacher.utils.ClassUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 请假审批
 * Created by Administrator on 2018/7/4 0004.
 */

public class TeacherRatifyLeaveListActivity extends BaseActivity implements View.OnClickListener, SrfManager.OnPullRefreshListener {

    private ImageView ivBack;
    private RecyclerView rv;
    private SmartRefreshLayout srf;
    private RelativeLayout rlLoadingView;
    private RelativeLayout rlContent;
    private ImageView ivEdit;

    //标题栏的布局
    private LinearLayout llTitle;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;

    //是否获取班级列表数据完成的标识,没完成之前点击选择班级的弹框提示正在加载,不允许点击
    private boolean isLoadClassCompleted;

    //列表的数据集合
    private List<LeaveInfo.DataBean> oldDatas;

    //空视图
    private View emptyView;

    //适配器
    private LeaveRvAdapter adapter;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.teacher_activity_ratify_leave_list;
    }

    @Override
    protected void init() {

        showContent();

        //初始化视图
        initView();

        //初始化下拉刷新控件
        initSrf();

        //获取推送过来的班级号
        initIntent();

        //请求班级数据
        httpClass();
    }


    /**
     * 初始化下拉刷新
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, this);
        srf.setPrimaryColors(getResources().getColor(R.color.transparent), getResources().getColor(R.color.white));
    }

    /**
     * 获取推送过来的班级号
     */
    private void initIntent() {
        String classNum = getIntent().getStringExtra("classnum");
        if (TextUtils.isEmpty(classNum)) {
            popSelectedPos = 0;
        } else {
            popSelectedPos = Integer.valueOf(classNum) - 1;
        }
    }


    /**
     * 初始化视图
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        rv = findViewById(R.id.rv);
        srf = findViewById(R.id.srf);
        rlLoadingView = findViewById(R.id.rl_loading);
        rlLoadingView.setVisibility(View.VISIBLE);
        ivEdit = findViewById(R.id.iv_choose_class);
        ivEdit.setOnClickListener(this);
        rlContent = findViewById(R.id.rl_content);
        rlContent.setVisibility(View.GONE);
        //标题栏
        llTitle = findViewById(R.id.ll_title);
    }


    /**
     * 弹出展示班级列表的方法
     */
    private void showClassPop() {
        ClassPoputil.showClassPop(this, classInfos, popSelectedPos, llTitle, new ClassPoputil.onPopItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                //记录当前点击条目的位置
                popSelectedPos = pos;

                //请求页面数据
                httpPageData(popSelectedPos, BqaManager.NORML);
            }
        });
    }

    /**
     * 请求班级里列表数据
     */
    private void httpClass() {
        ClassUtil.httpClass(rlLoadingView, this, new ClassUtil.onSuccessListener() {
            @Override
            public void onSuccess(List<ClassInfo.ListBean> datas) {
                //回调班级数据
                classInfos = datas;

                //改变加载完成的标记
                isLoadClassCompleted = true;

                //设置数据
                initRv();

                //请求页面列表数据
                httpPageData(popSelectedPos, BqaManager.NORML);
            }

            @Override
            public void hasNoData() {
                ivEdit.setVisibility(View.INVISIBLE);
            }
        });
    }


    /**
     * 设置列表
     */
    private void initRv() {
        oldDatas = new ArrayList<>();
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view, null);
        TextView tvMsg = emptyView.findViewById(R.id.tv_content);
        tvMsg.setText("暂时没有新的请假信息");
        adapter = new LeaveRvAdapter(this, R.layout.teacher_rv_leave_list, oldDatas);
    }


    /**
     * 请求页面数据
     *
     * @param popSelectedPos
     * @param method
     */
    private void httpPageData(int popSelectedPos, int method) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "2");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("apptoken", AccountUtils.getAccount(this));
        map.put("classnum", classInfos.get(popSelectedPos).getClassnum());
        map.put("platform", "8");


        HttpUtils.post(HttpAdress.TEACHERLEAVELIST, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                BqaManager.setErrorNet(rlLoadingView, srf, method, adapter);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoadingView != null && rlLoadingView.getVisibility() == View.VISIBLE) {
                    rlLoadingView.setVisibility(View.GONE);
                }
                if (rlContent != null && rlContent.getVisibility() != View.VISIBLE) {
                    rlContent.setVisibility(View.VISIBLE);
                }

                if (!TextUtils.isEmpty(response)) {
                    LeaveInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, LeaveInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            List<LeaveInfo.DataBean> newDatas = info.getData();
                            if (newDatas != null) {
                                if (method == BqaManager.NORML) {
                                    oldDatas.clear();
                                    oldDatas.addAll(newDatas);
                                    BqaManager.setRv(emptyView, TeacherRatifyLeaveListActivity.this, adapter, rv);
                                } else {
                                    //更新数据
                                    BqaManager.updateRvBySmf(method, srf, rv, oldDatas, newDatas, adapter);
                                    adapter.setEnableLoadMore(false);
                                }
                            }
                        } else {
                            UiUtils.Toast(Constants.ERRORSTATE + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }

                    } else {
                        Log.i("test", Constants.EMPTY);
                    }

                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.iv_choose_class) {
            //选择班级
            if (isLoadClassCompleted) {
                //弹出选择班级的PopUpWindow
                showClassPop();
            } else {
                //没加载完成
                SnackbarUtil.ShortSnackbar(llBaseMain, Constants.LOADING, 0).show();
            }
        }
    }

    /**
     * 下拉刷新
     *
     * @param refreshlayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
    }

    @Override
    protected void onDestroy() {
        if (adapter != null) {
            adapter.releaseHandler();
            adapter = null;
        }
        super.onDestroy();
    }
}
